{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "均方损失函数\n",
    "$loss(x_i,y_i)=(x_i-y_i)^2$\n",
    "很多的 loss 函数都有 size_average 和 reduce 两个布尔类型的参数。因为一般损失函数都是直接计算 batch 的数据，因此返回的 loss 结果都是维度为 (batch_size, ) 的向量"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1.],\n",
      "        [1., 1.]])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "\n",
    "loss_fn = torch.nn.MSELoss(reduction=\"none\")\n",
    "a = np.array([[1, 2], [3, 4]])\n",
    "b = np.array([[2, 3], [4, 5]])\n",
    "input = torch.autograd.Variable(torch.from_numpy(a))\n",
    "target = torch.autograd.Variable(torch.from_numpy(b))\n",
    "# loss应该是\n",
    "loss = loss_fn(input.float(), target.float())\n",
    "print(loss)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 返回平均值"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(7.5000)\n"
     ]
    }
   ],
   "source": [
    "loss_fn = torch.nn.MSELoss(reduction='mean')\n",
    "a = np.array([[1, 2], [3, 4]])\n",
    "b = np.array([[2, 4], [6, 8]])\n",
    "input = torch.autograd.Variable(torch.from_numpy(a))\n",
    "target = torch.autograd.Variable(torch.from_numpy(b))\n",
    "loss = loss_fn(input.float(), target.float())\n",
    "# 损失应该是[[1,2],[3,4]],计算均值的话就是1^1+2^2+3^2+4^2=1+4+9+16=30\n",
    "print(loss)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "$(a-b)$=[[1,2],[3,4]]\n",
    "计算均值的话就是\n",
    "$1^1+2^2+3^2+4^2=1+4+9+16=30$\n",
    "$\\frac{30}{4}=7.5$"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}